package com.example.administrator.myapplication.formdetail;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;

import com.example.administrator.myapplication.R;
import com.example.administrator.myapplication.data.Task;
import com.example.administrator.myapplication.data.source.TaskRepository;
import com.example.administrator.myapplication.data.source.local.TaskLocalDataSource;
import com.example.administrator.myapplication.form.FormActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

public class FormDetailActivity extends AppCompatActivity
        implements View.OnClickListener, AdapterView.OnItemSelectedListener,
        FormDetailContract.View{

    private static final String TAG = FormActivity.class.getSimpleName();
    private EditText mEtName, mEtPosition, mEtUseNumber, mEtDate;
    private Spinner mBrand;
    private RadioGroup mGroup;
    private RadioButton mRbYes, mRbNo;
    private Button mBtnCamera, mBtnSave;
    private MyRecyclerView mImgRecycler;

    private static int REQUEST_THUMBNAIL = 1;// 请求缩略图信号标识
    private static int REQUEST_ORIGINAL = 2;// 请求原图信号标识

    //放置图片的文件夹路径
    public static final String DIR_PATH = Environment.getExternalStorageDirectory().getPath() + "/sanshang/photo/";

    private Task task = null;
    //存储图片的List
    private List<String> mImgPathList = new ArrayList<>();
    //存储一个显示的spinner品牌
    private String brandStr = "";
    //存储所有的品牌数据
    private String[] brandArray;
    //存放照片的路径
    private String fileName;
    private long date;

    private ImageRecyclerAdapter imageRecyclerAdapter;

    private FormDetailPresenter mPresenter;

    private String action;//判断是来自什么请求的action


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_form_detail);
        brandArray = getResources().getStringArray(R.array.brand);

        mPresenter = new FormDetailPresenter(
                TaskRepository.getInstance(TaskLocalDataSource.getInstance(this)),
                this);
        initView();
        initListeners();

        Intent intent = getIntent();
        action = intent.getAction();

        if (action != null && action.equals("update")) {//页面处理更新页面逻辑
            task = intent.getParcelableExtra("task");
            initDatasNeedUpdate();
        }else{//页面处理添加数据逻辑
            task = new Task();
            initDatasNeedAdd();
        }

        File dir = new File(DIR_PATH);
        if (!dir.exists()) {
            dir.mkdirs();
            Log.i(TAG, "onCreate: " + dir.getAbsolutePath());
        }




    }

    private void initView() {
        mEtName = findViewById(R.id.name);
        mEtPosition = findViewById(R.id.position);
        mBrand = findViewById(R.id.brand);
        mEtUseNumber = findViewById(R.id.use_number);
        mEtDate = findViewById(R.id.date);
        mGroup = findViewById(R.id.radio_group);
        mRbYes = findViewById(R.id.rb_yes);
        mRbNo = findViewById(R.id.rb_no);
        mBtnCamera = findViewById(R.id.btn_camera);
        mBtnSave = findViewById(R.id.btn_save);
        mImgRecycler = findViewById(R.id.image_recycler);
        imageRecyclerAdapter = new ImageRecyclerAdapter(mImgPathList);
        mImgRecycler.setLayoutManager(new LinearLayoutManager(this,
                LinearLayoutManager.HORIZONTAL,false));
        mImgRecycler.setAdapter(imageRecyclerAdapter);
    }

    private void initListeners() {
        mBtnCamera.setOnClickListener(this);
        mBtnSave.setOnClickListener(this);
        mEtDate.setOnClickListener(this);
        mBrand.setOnItemSelectedListener(this);
    }

    private void initDatasNeedUpdate(){
        mEtName.setText(task.getName());
        mEtPosition.setText(task.getPosition());
        int pipeOut = task.getPipeOut();
        if (pipeOut == 1){//老化
            mRbYes.setChecked(true);
        }else{
            mRbNo.setChecked(true);
        }
        brandStr = task.getBrand();
        for (int i = 0; i < brandArray.length; i++) {
            if (brandArray[i].equals(brandStr)){
                mBrand.setSelection(i);
            }
        }
        float consumption = task.getConsumption();
        mEtUseNumber.setText(String.valueOf(consumption));
        date = task.getDate();
        mEtDate.setText(mPresenter.formatDate(date));
        mImgPathList = task.getImgPath();
        imageRecyclerAdapter.replaceData(mImgPathList);
        imageRecyclerAdapter.notifyDataSetChanged();
    }


    private void initDatasNeedAdd(){
        brandStr = brandArray[0];
        date = System.currentTimeMillis();
        mImgPathList = new ArrayList<>();
        mEtDate.setText(mPresenter.formatDate(date));
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_camera:
                startCameraWithOriginal();
                break;
            case R.id.btn_save:
                save();
                break;
            case R.id.date:
                //open 日期选择器
                openDatePicker();
                break;
            default:
                break;

        }
    }


    private void startCameraWithThubnail() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, REQUEST_THUMBNAIL);
    }

    /**
     * 打开照相机
     */
    private void startCameraWithOriginal() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(DIR_PATH, fileName);
        Uri uri = Uri.fromFile(new File(file.getAbsolutePath()));
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, REQUEST_ORIGINAL);

    }


    /**
     * 拍照成功后，把图片地址存到对象的地址集合，并且通知recyclerView进行局部刷新
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_THUMBNAIL) {
                Bundle bundle = data.getExtras();
                Bitmap bitmap = (Bitmap) bundle.get("data");
            } else if (requestCode == REQUEST_ORIGINAL) {
                mImgPathList.add(DIR_PATH+fileName);
//                imageRecyclerAdapter.addData(DIR_PATH+fileName);
                Log.i(TAG, "onActivityResult: mImgPathList.size = "+mImgPathList.size());
                imageRecyclerAdapter.notifyItemInserted(mImgPathList.size()-1);
            }
        }
    }

    private void openDatePicker() {
        Calendar c = Calendar.getInstance();
        DatePickerDialog datePickerDialog = new DatePickerDialog(FormDetailActivity.this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {

                        String m = String.valueOf(month+1);
                        mEtDate.setText(year + "年" + m + "月" + dayOfMonth + "日");
                        Calendar calendar = Calendar.getInstance();
                        calendar.set(Calendar.YEAR,year);
                        calendar.set(Calendar.MONTH,month);
                        calendar.set(Calendar.DAY_OF_MONTH,dayOfMonth);
                        date = calendar.getTimeInMillis();

//                        task.setDate(date);

//                        Date d = new Date(time);

                    }
                }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.show();
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        brandStr = brandArray[position];
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    @Override
    public void setPresenter(FormDetailContract.Presenter presenter) {

    }


    /**
     * 保存成功后需要finish页面，并且刷新列表页
     */
    @Override
    public void save() {

        if (mEtName.getText().toString().trim().length() == 0){
            Toast.makeText(this, "请输入姓名！！！", Toast.LENGTH_SHORT).show();
            return;
        }
        task.setName(mEtName.getText().toString());

        if (mEtPosition.getText().toString().trim().length() == 0){
            Toast.makeText(this, "请输入地址！！！", Toast.LENGTH_SHORT).show();
            return;
        }
        task.setPosition(mEtPosition.getText().toString());
        task.setBrand(brandStr);
        task.setPipeOut(mRbYes.isChecked() ? 1 : 0);
        if (mEtUseNumber.getText().toString().trim().length() == 0){
            Toast.makeText(this, "请输入用气量！！！", Toast.LENGTH_SHORT).show();
            return;
        }
        task.setConsumption(Float.parseFloat(mEtUseNumber.getText().toString()));

        task.setDate(date);
        task.setImgPath(mImgPathList);
        if (action.equals("update")){
            mPresenter.update(task);
        }else{
            task.setId(UUID.randomUUID().toString());
            Log.i(TAG, "save: >>>>>>>>>>>>>>>>>>");
            mPresenter.save(task);
        }

        // TODO: 2017/11/28  finish页面，并且刷新列表页
//        Intent it = new Intent();
//        it.putExtra("data",task);
//        setResult(100,it);
//        finish();

        setResult(100);
        finish();


    }

    private void checkEditNotNull() {

    }
}
